package com.bootdo.lgs.lgsInterfaces.blc.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.TypeReference;
import com.bootdo.common.exception.ParmException;
import com.bootdo.common.model.BdConstant;
import com.bootdo.lgs.lgsInterfaces.acommon.service.impl.AcommonServiceImpl;
import com.bootdo.lgs.lgsInterfaces.blc.model.BlcTraceData;
import com.bootdo.lgs.lgsInterfaces.blc.service.BlcService;
import com.bootdo.lgs.order.model.LgsOrder;
import com.bootdo.lgs.orderbind.model.OrderBindUpdate;
import com.google.gson.JsonObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.xml.ws.WebServiceException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.concurrent.TimeUnit;

//@Profile(value = {"pro"})
@Service
public class BlcServiceImpl implements BlcService {
    private static final Logger logger = LoggerFactory.getLogger(BlcServiceImpl.class);

    @Autowired
    private RedisTemplate redisTemplate;

    final Base64.Encoder encoder = Base64.getEncoder();
    final String text = "147053543:1777989982914560";
    byte[] textByte = new byte[0];
    {
        try {
            textByte = text.getBytes("ISO-8859-1");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
    }

    @Override
    public List<BlcTraceData> getTraceDataByOrderId(String orderId) {
        List<BlcTraceData> result = new ArrayList<>();
        if(orderId==null)
            return result;
        String host = "http://api.so56.cc/bizweb";
        StringBuffer sb = new StringBuffer(host+"/services/web.Query/orderTracking/");
        JsonObject params = new JsonObject();
        params.addProperty("order_no", orderId);//0092670
        sb.append(params.toString());
        try {
            URL url = new URL(sb.toString());
            // 使用下列方法构造uri, 否则, {}会被视为非法字符
            URI uri = new URI(url.getProtocol(), url.getAuthority(),
                    url.getHost(), url.getPort(), url.getPath(),
                    url.getQuery(), url.getRef());
            HttpGet httpGet = new HttpGet(uri);
            //此处username和APIkey需要替换为具体的值，然后使用base64编码
            String s = encoder.encodeToString(textByte);
            httpGet.setHeader("Authorization", "Basic " + s);
            HttpClient httpClient = new DefaultHttpClient();
            HttpResponse response;
            response = httpClient.execute(httpGet);
            String content = EntityUtils.toString(response.getEntity(),"UTF-8");
            //将结果转化为json\再转化为java对象
            JSONArray jsonArr = JSON.parseObject(content).getJSONObject("value").getJSONArray("list");
            result = JSON.parseObject(jsonArr.toJSONString(), new TypeReference<List<BlcTraceData>>() {});
        } catch (ClientProtocolException e) {
            logger.warn("调用百路驰查询接口失败",e);
        } catch (IOException e) {
            logger.warn("调用百路驰查询接口失败",e);
        } catch (URISyntaxException e) {
            logger.warn("调用百路驰查询接口失败",e);
        }catch (Exception e){
            logger.warn("调用百路驰查询接口失败",e);
        }
        return result;
    }

    @Override
    public List<OrderBindUpdate> sendOrders(List<LgsOrder> lgsOrders) {
        List<OrderBindUpdate> result = new ArrayList<>();
        if(lgsOrders==null||lgsOrders.size()<1)
            return result;
        for(LgsOrder lgsOrder:lgsOrders){
            try {
                result.add( sendOrder(lgsOrder) );
            } catch (ParmException pe){
                logger.info(pe.getMessage(),pe);
            }catch (Exception e) {
                logger.info("下单失败:"+lgsOrder,e);
            }
        }
        return result;
    }

    @SuppressWarnings("Duplicates")
    @Override
    public OrderBindUpdate sendOrder(LgsOrder lgsOrder)throws Exception {
        OrderBindUpdate orderBindUpdate = new OrderBindUpdate();
        //String host = "http://api.app365.com/bizweb/services/web.Query/onlineOrder/"; //无效地址
        String host = "http://dev.so56.cc/bizweb/services/web.Query/onlineOrder/"; //正式地址

        JsonObject params = new JsonObject();
        params.addProperty("code", ""); //订单号
        params.addProperty("order_no", ""); //运单号（如填写，不能与现有单号重复）
        params.addProperty("order_date", lgsOrder.getOrder_date()); //运单日期(不填默认为当前时间)
        params.addProperty("customer_name", "雄帝科技"); //客户名称 *
        params.addProperty("doc_type_name", "专线"); //单据类型（专线、三方、快递，不填默认为专线）
        params.addProperty("origin_party_name", "深圳市雄帝科技股份有限公司"); //发货单位 *
        params.addProperty("origin_contact_name", StringUtils.isNotBlank(lgsOrder.getSender())==true?lgsOrder.getSender():"雄帝"); //发货联系人 *
        params.addProperty("origin_phone", StringUtils.isNotBlank(lgsOrder.getSender_phone())==true?lgsOrder.getSender_phone():"83416677"); //发货人电话 *
        params.addProperty("origin_mobile", StringUtils.isNotBlank(lgsOrder.getSender_phone())==true?lgsOrder.getSender_phone():""); //发货人手机(手机电话填写一个) *
        params.addProperty("origin_location_name", StringUtils.isNotBlank(lgsOrder.getSender_address())==true?lgsOrder.getSender_address():"深圳市雄帝科技"); //发货地址 *
        params.addProperty("dest_party_name", lgsOrder.getCustomer_name()); //收货单位 *
        params.addProperty("dest_contact_name", lgsOrder.getConsignee()); //收货联系人 *
        params.addProperty("dest_phone", lgsOrder.getConsignee_phone()); //收货人电话 *
        params.addProperty("dest_mobile", lgsOrder.getConsignee_phone()); //收货人手机 *
        params.addProperty("dest_location_name", lgsOrder.getConsignee_address()); //收货地址 *
        params.addProperty("cargo_name", lgsOrder.getGoods_name()); //货物名称 *
        params.addProperty("pack_qty", lgsOrder.getDelivery_qty()); //件数 *
        params.addProperty("gross_weight", "0.01"); //重量 *
        params.addProperty("volume", "0.01"); //体积 *
        params.addProperty("insurance_value",StringUtils.isNotBlank(lgsOrder.getValue_statement())==true?lgsOrder.getValue_statement():"0" ); //保价金额
        params.addProperty("settle_type_name", "月结"); //结算类型名称(现付、到付、回付、月结) *
        params.addProperty("description", StringUtils.isNotBlank(lgsOrder.getRemark())==true?lgsOrder.getRemark():"无"); //描述
        params.addProperty("dest_service_name", lgsOrder.getDelivery_method_nm()); //送货方式: 包车直送、服务商送货、站点送货、送货上门、送货上楼、客户自提 *
        params.addProperty("pack_mode_name", ""); //包装方式: 纸箱、木箱、防水袋、纸、编织袋、泡沫、木料、纸袋、纸筒、塑料桶、其他、托盘、木架、薄膜、铁桶、卷、纸箱+木架、无包装


            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(host);
            List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
            nameValuePair.add(new BasicNameValuePair("data", params.toString()));
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair,"UTF-8"));
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
            //String s = encodeBase64("登录QQ:API KEY ");
            logger.info("【百路驰】下单:"+lgsOrder);
            String s = encoder.encodeToString(textByte);
            //System.out.println(s);
            httpPost.setHeader("Authorization", "Basic " + s);
            HttpResponse response = httpClient.execute(httpPost);
        System.out.println("response:"+response);
            if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
                String result = EntityUtils.toString(response.getEntity());
                logger.info("调用【百路驰】下单接口返回:"+result);
                String status = JSON.parseObject(result).getString("status");
                if("Error".equals(status))
                    throw new ParmException("调用【百路驰】下单接口失败:返回结果状态error");
                String order_no = JSON.parseObject(result).getJSONObject("value").getJSONObject("data").getString("order_no");
                logger.info("【百路驰】下单成功:"+order_no);
                if(StringUtils.isNotBlank(order_no)){
                    orderBindUpdate.setId(lgsOrder.getId());
                    orderBindUpdate.setLgs_track_number(order_no);
                    try {
                        redisTemplate.opsForValue().set(BdConstant.LGS_ALREADY_SUCCESS_SAVE_ORDER_ID+lgsOrder.getId(),order_no,25, TimeUnit.HOURS);
                        logger.info("百路驰下单：保存物流成功订单号到缓存成功："+orderBindUpdate);
                    } catch (Exception e) {
                        logger.warn("百路驰下单：下单到物流成功，保存物流订单号到缓存失败:"+orderBindUpdate,e);
                    }
                }else{
                    throw new ParmException("调用【百路驰】下单接口成功：但是返回订单号为空，绑定单号失败");
                }
                return orderBindUpdate;
            }else{
                throw new ParmException("调用【百路驰】下单接口失败：返回状态不为200");
            }
    }


}
